var config = {

    logoMargin: 10,
    logoBorderWidth: 3,
    logoBorderRadius: 10,
    logoVerticalOffset: 50,
    fontSize: '20px',
    indent: '50px',
    pixelsBetweenItems: '50px',
    earthColor: '#855723',
    greenColor: '#74C365',
    blueColor: '#87CEEB'
}

var info = {

    shareSelected: 'none',
    extraGreens: 0,
    eggs: 0

}

function onResize(){

    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();

   centerLogo(); 

   centerFaqText();
}

function onPageLoad() {
    
    info.documentWidth = $( document ).width();
    info.documentHeight = $( document ).height();

    initializeModalBox();

    makeLogoPretty();
    
    makeIntroTextPretty();

    makeShareSizeElements();
    
    makeDeliveryLocationElements();

    makeCustomerInfoElements();

    makeOutOfTownElements();
    
    makeExtraGreensElements();
    
    makeEggsElements();

    makeOutroTextElements();

    makeAmountPaidElements();

}

function makeAmountPaidElements() {

    $('#amountPaid').css( { 'margin': '20px' } )
                    .append(
        makeEl('div').css( { 'margin-left': '20px',
                             'margin-right': '20px',
                             'float': 'left' } ).text( 'Amount Paid : ' ),
        makeEl('input').attr( { 'id': 'amountPaidValue', 'value': '0.00' } )
                       .css( { 'float': 'left',
                               'text-align': 'center',
                               'font-size': '30px',
                               'padding': '5px',
                               'line-height': '40px',
                               'border': '1px solid black' } ),
        makeEl('div').css( { 'clear': 'both' } ) );


}

function updateTotal() {

    info.total = ( info.eggsSubtotal )
            ? info.eggsSubtotal.toFixed(2)
            : ( info.extraGreens )
                ? info.greensSubTotal.toFixed(2)
                : info.weekSubtotal.toFixed(2);
    
    $('#totalPrice').text( [ 'Your share : $', info.total ].join('') );
}

function makeOutroTextElements() {


    $('#outroText').css( { 'margin-top': config.pixelsBetweenItems,
                           'min-width': '1036px',
                           'overflow': 'hidden',
                           'margin-left': config.indent,
                           'margin-right': config.indent } ).append(
        makeEl('div').css( { 'margin-bottom': '50px' } ).text( "By clicking the button below, I am contracting to purchase a share in the 2013 harvest from the Patchwork Gardens Community Supported Agriculture (CSA) program. I understand that Community Supported Agriculture is a partnership between the grower and the consumer. I understand that the grower will do their best to provide me with a generous helping of vegetables each week, but that agriculture is an inherently risky enterprise. Crop yield can be adversely affected by weather, pests, diseases and seasons shortened due to frost." ),
        makeEl('div').attr( { 'id': 'totalPrice' } )
                     .css( { 'text-align': 'center',
                             'margin-bottom': '20px',
                             'font-weight': 'bold',
                             'font-size': '30px',
                             'color': config.earthColor } ),
        makeEl('div').css( { 'text-align': 'center',
                             'margin-bottom': '30px',
                             'font-weight': 'bold' } ).text("Please mail full payment to Patchwork Gardens at 9057 W. Third St. Dayton, OH 45417"),
        makeEl('div').attr( { 'class': 'joinButton' } ).text('Join CSA!') );

    $('.joinButton').css( { 'margin-left': ( ( info.documentWidth - ( parseInt( config.indent ) * 2 ) - $('.joinButton').outerWidth( true ) ) / 2 ) } )
                    .bind( 'click', {}, handleJoinClick );
}

function showModalText( text ) {
 
    $('#modalBoxTitle').text( 'Not so fast' );
   
    $('#modalBoxForm').append(
        makeEl('div').attr( { 'class': 'modalText' } ).text( text ) );
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleJoinClick() {

    $('.joinButton').unbind('click');

    if( ! info.shareSelected ) { info.shareSelected = 'none'; }
    if( ! info.deliveryLocation ) { showModalText( 'Please select a delivery location.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }

    if( $.trim( $('#firstNameField').val() ) == '' || $.trim( $('#lastNameField').val() ) == '' ) {
    
        showModalText( 'Please enter your name.' );
        $('.joinButton').bind('click',{}, handleJoinClick);
        return;
    }

    if( $.trim( $('#emailField').val() ) == '' ) { showModalText( 'Please enter your email address.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }
    if( validateEmail() == false ) { showModalText( 'The email address you entered is invalid.  Please change it and try again.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }
    if( $.trim( $('#addressField').val() ) == '' ) { showModalText( 'Please enter your home address.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }
    if( $.trim( $('#phoneNumberField').val() ) == '' ) { showModalText( 'Please enter your phone number.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }
    if( $('.weekSelected').length == 20 ) { showModalText( 'Every week is grey.  You have indicated that you do not want produce for any week of the season.  Please revise the weeks you have selected.' ); $('.joinButton').bind('click',{}, handleJoinClick); return; }

    var weeksOutOfTown = [ ];

    $('.weekSelected').each(
        function( i ) {
            weeksOutOfTown.push( $( this ).attr( 'week' ) ); } );

    var url = [ 'http://patchworkgardens.net/cgi-bin/signThemUp.py?shareSize=',
                        encodeURIComponent( info.shareSelected ),
                        '&deliveryLocation=',
                        encodeURIComponent( info.deliveryLocation ),
                        '&firstName=',
                        encodeURIComponent( $.trim( $('#firstNameField').val() ) ),
                        '&lastName=',
                        encodeURIComponent( $.trim( $('#lastNameField').val() ) ),
                        '&address=',
                        encodeURIComponent( $.trim( $('#addressField').val() ) ),
                        '&phoneNumber=',
                        encodeURIComponent( $.trim( $('#phoneNumberField').val() ) ),
                        '&emailAddress=',
                        encodeURIComponent( $.trim( $('#emailField').val() ) ),
                        '&hearAboutUs=',
                        encodeURIComponent( $.trim( $('#hearAboutUsField').val() ) ),
                        '&weeksOutOfTown=',
                        encodeURIComponent( weeksOutOfTown.join(':') ),
                        '&extraGreens=',
                        encodeURIComponent( info.extraGreens ),
                        '&eggs=',
                        encodeURIComponent( info.eggs ),
                        '&totalPrice=',
                        encodeURIComponent( info.total ),
                        '&amountPaid=',
                        encodeURIComponent( $('#amountPaidValue').val() ),
                ].join('');

    $.ajax( { url: url,
              type: 'GET',
              error: handleErrorResponse,
              success: handleJoinResponse } );

    showModalWait();   
}

function validateEmail( ) {

    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test( $('#emailField').val())) {
       
        return true;

    } else {

        return false;

    }
}

function showModalWait() {

    $('#modalBoxTitle').text( '' );
    $('#modalBoxForm').append( makeEl('div').attr( { 'class': 'modalText' } ).text( 'Please Wait.' ) );

    info.modalWait = true;
    
    $('#modalBoxContainer').show( 'slow', alignModalBox );
}

function handleErrorResponse() {

    $( $('#modalBoxForm div.modalText')[0] ).text( 'There was an error.  Sorry for the inconvenience.  Please try again, or print, and mail us the form.' );
    info.modalWait = false;
    alignModalBox();
    $('.joinButton').bind('click',{}, handleJoinClick);
}

function handleJoinResponse( response ) {

    var responseObj = eval( '(' + response + ')' );

    if( responseObj.error == 'exactOrder' ) {

        $( $('#modalBoxForm div.modalText')[0] ).text( 'There is already an order exactly like this one.' );
        info.modalWait = false;
        alignModalBox();
        $('.joinButton').bind('click',{}, handleJoinClick);

        
    } else if( responseObj.error ) {

        $( $('#modalBoxForm div.modalText')[0] ).text( 'There was an error.  Sorry for the inconvenience.  Please try again, or print, and mail us the form.' );
        info.modalWait = false;
        alignModalBox();
        $('.joinButton').bind('click',{}, handleJoinClick);

    } else if( $.trim( responseObj.invalidEmail ) == 'True' ) {
        
        $( $('#modalBoxForm div.modalText')[0] ).text( 'We have signed you up!  Unfortunately, there was a problem sending you an email.  Either you entered an incorrect address, or there are problems on our end.  Please send us an email at eat.patchworkgardens@gmail.com so that we can communicate with you via email.  Thanks!' );
        alignModalBox();
        setTimeout( function() { closeModalBox(); window.location = 'http://patchworkgardens.net/csa.html'; }, 20000 );

    } else if( $.trim( responseObj.invalidEmail ) == 'False' ) {
        
        $( $('#modalBoxForm div.modalText')[0] ).text( 'You did it!  Welcome!' );
        alignModalBox();
        setTimeout( function() { closeModalBox(); window.location = 'http://patchworkgardens.net/csa.html'; }, 5000 );
    }
}

function makeEggsElements() {

    $('#eggs').css( { 'margin-top': config.pixelsBetweenItems,
                      'min-width': '1036px',
                      'overflow': 'hidden',
                      'margin-left': config.indent } ).append(
        makeEl('div').css( { 'font-size': config.fontSize,
                             'margin-bottom': '10px',
                             'color': config.greenColor,
                             'font-weight': 'bold' } ).text('What about eggs?'),
        makeEl('div').append(
            makeEl('div').css( { 'float': 'left', 'margin-right': '40px' } )
                         .width( '75%' )
                        .text("Would you like eggs from free-range, pastured chickens?  Keener Farm, our neighbor, is offering eggs from free-range, pastured poultry, which are available as an extra through our CSA.  The cost is $5 for a dozen eggs.  Enter the number of egg cartons ( containing 12 eggs ) you would like with each box of produce to the right."),
            makeEl('input').attr( { 'id': 'eggsBox', 'value': '0' } )
                           .css( { 'float': 'left',
                                   'text-align': 'center',
                                   'font-size': '30px',
                                   'padding': '5px',
                                   'line-height': '40px',
                                   'border': '1px solid black' } )
                         .hover( setMouseToPointer, setMouseToDefault )
                         .hover( handleBoxHover, handleBoxLeaveHover )
                         .bind( 'keydown', { }, handleEggsKeyDown )
                         .width( 40 ).height( 36 ),
            makeEl('div').css( { 'clear': 'both' } ) ),
        makeEl('div').attr( { 'id': 'eggsSubtotal' } ).css( { 'margin-top': '20px', color: config.earthColor, 'font-weight': 'bold' } ).hide() );
}

function makeExtraGreensElements() {

    $('#extraGreens').css( { 'margin-top': config.pixelsBetweenItems,
                             'min-width': '1036px',
                             'overflow': 'hidden',
                             'margin-left': config.indent } ).append(
        makeEl('div').css( { 'font-size': config.fontSize,
                             'margin-bottom': '10px',
                             'color': config.greenColor,
                             'font-weight': 'bold' } ).text('Do you love greens?'),
        makeEl('div').append(
            makeEl('div').css( { 'float': 'left', 'margin-right': '40px' } )
                         .width( '75%' )
                         .html(  "Can&lsquo;t get enough Kale, Lettuce, Swiss Chard, or any of the other flavorful greens that are bountiful in the first weeks of the season?  For an additional $50, you can receive an extra bag of greens each week later in the season ( about 15 weeks ).  Enter the number of extra bags of greens you would like to the right."),
            makeEl('input').attr( { 'id': 'extraGreensBox', 'type': 'text', 'value': '0' } )
                         .css( { 'text-align': 'center',
                                 'font-size': '30px',
                                 'float': 'left',
                                 'padding': '5px',
                                 'line-height': '40px',
                                 'border': '1px solid black' } )
                         .hover( setMouseToPointer, setMouseToDefault )
                         .hover( handleBoxHover, handleBoxLeaveHover )
                         .bind( 'keydown', { }, handleExtraGreensKeyDown )
                         .width( 40 ).height( 36 ),
            makeEl('div').css( { 'clear': 'both' } ) ),
        makeEl('div').attr( { 'id': 'extraGreensSubtotal' } )
                     .height( 20 )
                     .css( { 'margin-top': '20px',
                             'color': config.earthColor,
                             'font-weight': 'bold' } ).hide() );
}

function handleEggsKeyDown( e ) {

   var key = e.keyCode || e.which;

   stringKey = String.fromCharCode( key );

   var regex = /[0-9]/;

   if( ! regex.test( stringKey ) ) {

       if( e.keyCode == 8 || e.keyCode == 46 ) {
      
           setTimeout( function() { updateEggsSubtotal(); updateTotal(); }, 200 );
      
       } else if( e.keyCode == 37 || e.keyCode == 39 ) {

           return;

       } else {

           e.returnValue = false;

           if( e.preventDefault ) { e.preventDefault(); }
       }

   } else {

       setTimeout( function() { updateEggsSubtotal(); updateTotal(); }, 200 );
   }
}

function handleExtraGreensKeyDown( e ) {

   var key = e.keyCode || e.which;

   stringKey = String.fromCharCode( key );

   var regex = /[0-9]/;

   if( ! regex.test( stringKey ) ) {

       if( e.keyCode == 8 || e.keyCode == 46 ) {
      
           setTimeout( function() { updateExtraGreensSubtotal(); updateEggsSubtotal(); updateTotal(); }, 200 );
      
       } else if( e.keyCode == 37 || e.keyCode == 39 ) {

           return;

       } else {

           e.returnValue = false;

           if( e.preventDefault ) { e.preventDefault(); }
       }

   } else {

       setTimeout( function() { updateExtraGreensSubtotal(); updateEggsSubtotal(); updateTotal(); }, 200 );
   }
}

function updateEggsSubtotal() {

    var eggsInput = $('#eggsBox');

    if( $.trim( eggsInput.val() ) == '' ) {
        info.eggs = 0;
    } else if ( eggsInput.val() > 9 ) {
        info.eggs = 9;
        eggsInput.val('9');
    } else {
        info.eggs = parseInt( eggsInput.val() );
    }

    if( info.eggs ) {

        var extraGreensSubtotal = ( info.extraGreens ) ? ( info.extraGreens * 50 ) : 0;

        info.eggsSubtotal = info.weekSubtotal + extraGreensSubtotal + ( ( 5 * info.eggs ) * ( 20 - $('.weekSelected').length ) );

        var text = [ 'Subtotal : $', info.eggsSubtotal.toFixed(2), ' ( ', ];
        
        if( info.extraGreens ) {

            text = text.concat( [
                info.greensSubTotal.toFixed(2),
                ' from previous subtotal plus $',
                ( ( 5 * info.eggs ) * ( 20 - $('.weekSelected').length ) ).toFixed(2), ' )' ] );

        } else {
            
            text = text.concat( [
                info.weekSubtotal.toFixed(2),
                ' from previous subtotal plus $',
                ( ( 5 * info.eggs ) * ( 20 - $('.weekSelected').length ) ).toFixed(2), ' )' ] );
        }

        $('#eggsSubtotal').text( text.join('') ).show('slow');

    } else {
        
        info.eggsSubtotal = info.greensSubTotal;
    
        $('#eggsSubtotal').hide('slow');

    }
}

function updateExtraGreensSubtotal() {

    var greensInput = $('#extraGreensBox');

    if( $.trim( greensInput.val() ) == '' ) {
        info.extraGreens = 0;
    } else if ( greensInput.val() > 9 ) {
        info.extraGreens = 9;
        greensInput.val('9');
    } else {
        info.extraGreens = parseInt( greensInput.val() );
    }
    
    if( info.extraGreens ) {

        var text = [ 'Subtotal : $', ( info.weekSubtotal + ( parseInt( info.extraGreens ) * 50 ) ).toFixed(2), ' ( ', info.weekSubtotal.toFixed(2), ' from previous subtotal plus $', parseInt( info.extraGreens ) * 50, ' )' ].join('');

        info.greensSubTotal = info.weekSubtotal + ( parseInt( info.extraGreens ) * 50 );

        $('#extraGreensSubtotal').text( text ).show('slow');

    } else {
        
        info.greensSubTotal = info.weekSubtotal;
    
        $('#extraGreensSubtotal').hide('slow');
    }


}

function makeOutOfTownElements() {

    var csaWeeks = [
        'May 15/16',
        'May 22/23',
        'May 29/30',
        'June 5/6',
        'June 12/13',
        'June 19/20',
        'June 26/27',
        'July 3/4',
        'July 10/11',
        'July 17/18',
        'July 24/25',
        'J/A 31/1',
        'Aug 7/8',
        'Aug 14/15',
        'Aug 21/22',
        'Aug 28/29',
        'Sept 4/5',
        'Sept 11/12',
        'Sept 18/19',
        'Sept 25/26'
    ];

    var dateContainer = makeEl('div').css( { 'margin-top': '20px' } );

    for( var i = 0, ii = csaWeeks.length; i < ii; i++ ) {

        dateContainer.append(
            makeEl( 'div' ).attr( { 'week': i } )
                           .css( { 'float': 'left',
                                   'text-align': 'center',
                                   'border': '1px solid black' } )
                           .width( 40 )
                           .text( csaWeeks[i] )
                           .hover( setMouseToPointer, setMouseToDefault )
                           .bind( 'click', { }, handleDateClick )
        );
    }

    dateContainer.append( makeEl('div').css( { 'clear': 'both' } ) );

    $('#outOfTown').css( { 'margin-top': config.pixelsBetweenItems,
                           'min-width': '1036px',
                           'overflow': 'hidden',
                           'margin-left': config.indent,
                           'margin-right': config.indent } ).append(
        makeEl('div').css( { 'margin-right': '50px',
                             'margin-bottom': '20px',
                             'font-weight': 'bold',
                             'color': config.greenColor,
                             'font-size': config.fontSize } ). text( 'What if you are going to be out of town in the summer?' ),
        makeEl('div').text( 'If you are going to be out of town during the summer, you may take that as an opportunity to share your box of local, sustainably grown vegetables with a friend or neighbor. If you are going to be gone for some period of time during the season and would not like to share your vegetables with a friend, or if you would just like to save the money, we need to know ahead of time. With sufficient notice, we will not charge you for weeks you are not able to pick up your vegetables. If you already know when you will be out of town, please let us know by clicking on the weeks you will be gone below.  A grey background for a date denotes a week that you do not wish to receive produce.' ),
        dateContainer,
        makeEl('div').attr( { 'id': 'weekSubtotal' } )
                     .css( { 'margin-top': '20px', color: config.earthColor, 'font-weight': 'bold' } )
                     .height( 20 ).hide()
    );
}

function handleDateClick() {

    var el = $(this);

    if( el.hasClass('weekSelected') ) {
        el.css( { 'background-color': '' } ).removeClass('weekSelected');
    } else {
        el.css( { 'background-color': 'grey' } );
        el.addClass( 'weekSelected' );
    }

    updateWeekSubtotal();
    updateExtraGreensSubtotal();
    updateEggsSubtotal();
    updateTotal();

}

function makeCustomerInfoElements() {

    $('#customerInfo').css( { 'margin-top': config.pixelsBetweenItems,
                              'min-width': '1036px',
                              'overflow': 'hidden',
                              'margin-left': config.indent,
                              'font-size': config.fontSize } ).append(
       makeEl('div').css( { 'color': config.greenColor,
                            'margin-bottom': '20px',
                            'font-weight': 'bold' } ).text( 'Tell us about yourself : ' ),
       makeEl('div').append(
           makeEl('div').css( { 'float': 'left', 'margin-right': '50px' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'First Name : ' ),
               makeEl('input').attr( { 'id': 'firstNameField',
                                       'type': 'text',
                                       'size': '23',
                                       'name': 'name' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'float': 'left', 'margin-right': '50px' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Last Name : ' ),
               makeEl('input').attr( { 'id': 'lastNameField',
                                       'type': 'text',
                                       'size': '23',
                                       'name': 'name' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'float': 'left' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Phone Number : ' ),
               makeEl('input').attr( { 'id': 'phoneNumberField', 
                                       'type': 'text',
                                       'size': '15',
                                       'name': 'phoneNumber' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'clear': 'both' } ) ),
       makeEl('div').css( { 'margin': '20px 0' } ).append(
           makeEl('div').css( { 'float': 'left', 'margin-right': '50px' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Email : ' ),
               makeEl('input').attr( { 'id': 'emailField',
                                       'type': 'text',
                                       'size': '30',
                                       'name': 'emailAddress' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'float': 'left' } ).append(
               makeEl('div').css( { 'float': 'left',
                                    'padding': '5px',
                                    'font-weight': 'bold' } ).text( 'Home Address : ' ),
               makeEl('input').attr( { 'id': 'addressField', 
                                       'type': 'text',
                                       'size': '70',
                                       'name': 'homeAddress' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'clear': 'both' } ) ),
       makeEl('div').append(
           makeEl('div').css( { 'float': 'left',
                                'padding': '5px',
                                'font-weight': 'bold' } ).text( 'How did you hear about us ?' ),
               makeEl('input').attr( { 'id': 'hearAboutUsField',
                                       'type': 'text',
                                       'size': '100',
                                       'name': 'howDoTheyKnow' } )
                              .css( { 'padding': '5px' } ) ),
           makeEl('div').css( { 'clear': 'both' } ) );
}

function makeDeliveryLocationElements() {

    var locationStructure = [

        { text: 'Dayton',
          value: '1',
          time: 'Wed 4-6pm',
          address: '30 Sawmill Rd'
        },

        { text: 'Kettering',
          value: '5',
          time: 'Wed 4-8pm',
          address: '2675 Patterson Rd (Liberty Market)'
        },

        { text: 'Yellow Springs',
          value: '4',
          time: 'Thurs 2-6pm',
          address: "1485 Xenia Ave (Dollar General Farmer's Market)"
        },

        { text: 'Cincinnati',
          value: '3',
          time: 'Wed 530-7pm',
          address: '8140 Leeshore Dr (Maineville)'
        },

        { text: 'Patchwork Gardens',
          value: '6',
          time: 'Wed 5-7pm',
          address: '9057 W Third St'
        },

        { text: "Sugar Creek Farmer's Market",
          value: '2',
          time: 'Fri 3-5pm',
          address: '4333 Feedwire Rd (Next to Petsmart)'
        },

        { text: 'I\'m in a group of 5 or more people',
          value: '0',
          time: 'to be determined',
          address: ''
        }
    ];

    var locationContainer = makeEl('div').css( { 'font-size': '14px', 'margin-top': '10px' } ) ;

    for( var i = 0, ii = locationStructure.length; i < ii; i++ ) {

        locationContainer.append(
            makeEl('div').attr( { 'class': 'deliveryBox' } )
                         .css( { 'float': 'left', 'padding': '10px', 'margin': '17px', 'border': '1px solid black' } )
                         .hover( setMouseToPointer, setMouseToDefault )
                         .hover( handleBoxHover, handleBoxLeaveHover )
                         .bind( 'click', { value: locationStructure[i].value }, handleDeliveryLocationClick )
                         .append(
                makeEl( 'div' ).css( { 'float': 'left' } ).append( 
                    makeEl('div').text( [ locationStructure[i].text, ' (', locationStructure[i].time, ')' ].join('') ),
                    makeEl('div').text( locationStructure[i].address ) ) ) );
    }
            
    locationContainer.append( makeEl('div').css( { 'clear': 'both' } ) );

    $('#deliveryLocation').css( { 'margin-top': config.pixelsBetweenItems,
                                  'min-width': '1036px',
                                  'overflow': 'hidden',
                                  'font-size': config.fontSize,
                                  'margin-left': config.indent } ).append(
        makeEl('div').css( { 'font-weight': 'bold',
                             'color': config.greenColor } ).text( 'Delivery Time / Location ( click to select ) : Have a group of 5 or more people?  Contact us for additional delivery options.' ),
        locationContainer );
}

function handleDeliveryLocationClick( e ) {

   $('.deliveryBox').css( { 'border': '1px solid black', 'margin': '17px' } );

   $( this ).css( { 'border': [ '7px solid ', config.blueColor ].join(''),
                    'margin': '11px' } );

   info.deliveryLocation = e.data.value;
}

function handleBoxHover( e ) {
    
    $(this).css( { 'background-color': config.blueColor } );
}

function handleBoxLeaveHover( e ) {
    
    $(this).css( { 'background-color': '' } );
}

function handleLargeShareClick() {

    if( info.shareSelected == 'large' ) {
        $('#largeShareBox').css( { 'background-image': '' } );
        info.shareSelected = 'none';
        removeWeekSubtotal();
        removeExtraGreensSubtotal();
        removeEggsSubtotal();
    } else if( info.shareSelected == 'small' || info.shareSelected == 'none' ) {
        $('#smallShareBox').css( { 'background-image': '' } );
        $('#largeShareBox').css( { 'background-image': 'url(Images/checkmark.png)' } );
        info.shareSelected = 'large';
        updateWeekSubtotal();
        updateExtraGreensSubtotal();
        updateEggsSubtotal();
        updateTotal();
    }
}

function handleSmallShareClick() {
   
    if( info.shareSelected == 'small' ) {
        $('#smallShareBox').css( { 'background-image': '' } );
        info.shareSelected = 'none';
        removeWeekSubtotal();
        removeExtraGreensSubtotal();
        removeEggsSubtotal();
    } else if( info.shareSelected == 'large' || info.shareSelected == 'none' ) {
        $('#largeShareBox').css( { 'background-image': '' } );
        $('#smallShareBox').css( { 'background-image': 'url(Images/checkmark.png)' } );
        info.shareSelected = 'small';
        updateWeekSubtotal();
        updateExtraGreensSubtotal();
        updateEggsSubtotal();
        updateTotal();

    }
}

function removeExtraGreensSubtotal() {
    
    $('#extraGreensSubtotal').hide( 'slow' );
}

function removeEggsSubtotal() {
    
    $('#eggsSubtotal').hide( 'slow' );
}

function removeWeekSubtotal() { $('#weekSubtotal').hide('slow'); }

function updateWeekSubtotal() {

    var text = [ 'Subtotal : ' ];

    if( info.shareSelected == 'small' ) {

        info.weekSubtotal = 350 - ( 17.5 * $('.weekSelected').length );

        text.push( '$' );
        text.push( info.weekSubtotal.toFixed(2) );
        text.push( ' ( $350 small share minus ' );
        text.push( $('.weekSelected').length );
        text.push( ' week(s) out of town )' );

    } else if( info.shareSelected == 'large' ) {

        info.weekSubtotal = 500 - ( 25 * $('.weekSelected').length );

        text.push( '$' );
        text.push( info.weekSubtotal.toFixed(2) );
        text.push( ' ( $500 large share minus ' );
        text.push( $('.weekSelected').length );
        text.push( ' week(s) out of town )' );

    } else {

        info.weekSubtotal = 0;

        text.push( 'There is no share size selected.' );
    }

    $('#weekSubtotal').text( text.join('') );

    if( $('#weekSubtotal').is(':hidden') ) { $('#weekSubtotal').show( 'slow' ); }
}

function makeShareSizeElements() {

    $('#shareSize').css( { 'margin-top': config.pixelsBetweenItems,
                           'height': '40px',
                           'line-height': '40px',
                           'min-width': '1036px',
                           'overflow': 'hidden',
                           'font-size': config.fontSize,
                           'margin-left': config.indent } ).append(
        makeEl('div').css( { 'float': 'left',
                             'font-weight': 'bold',
                             'color': config.greenColor,
                             'margin-right': '50px' } ).text( 'Share Size (click on a box to select) : ' ),
        makeEl('div').css( { 'float': 'left' } ).text('Large ('),
        makeEl('div').css( { 'float': 'left', 'font-weight': 'bold', color: config.earthColor, 'margin-right': '5px' } ).text('$500 '),
        makeEl('div').css( { 'float': 'left', 'margin-right': '20px' } ).text(' for 20 weeks)'),
        makeEl('div').css( { 'float': 'left',
                             'margin-top': '0px',
                             'border': '1px solid black' } )
                     .attr( { 'id': 'largeShareBox' } )
                     .hover( setMouseToPointer, setMouseToDefault )
                     .hover( handleBoxHover, handleBoxLeaveHover )
                     .click( handleLargeShareClick )
                     .width( 40 ).height( 36 ),
        makeEl('div').css( { 'float': 'left',
                             'margin-left': '60px' } ).text('Small ('),
        makeEl('div').css( { 'float': 'left', 'font-weight': 'bold', color: config.earthColor, 'margin-right': '5px' } ).text('$350 '),
        makeEl('div').css( { 'float': 'left', 'margin-right': '20px' } ).text(' for 20 weeks)'),
        makeEl('div').css( { 'float': 'left',
                             'margin-top': '0px',
                             'border': '1px solid black' } )
                     .attr( { 'id': 'smallShareBox' } )
                     .hover( setMouseToPointer, setMouseToDefault )
                     .hover( handleBoxHover, handleBoxLeaveHover )
                     .click( handleSmallShareClick )
                     .width( 40 ).height( 36 ),
        makeEl('div').css( { 'clear': 'both' } ) );
}

function centerLogo() {

    $('#logoContainer')
        .css( { 'margin-left': ( ( info.documentWidth - $('#logoBorder1').outerWidth( true ) ) / 2 ) } );
}

function makeLogoPretty() {

    $('#logoImage')
        .css( { 'float': 'left',
                'background-image': 'url(Images/jsLogo.png)',
                'height': '209px',
                'width': '540px',
                'margin': [ config.logoMargin, 'px' ].join('') } );
    
    $('#logoBorder3').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.earthColor ].join('') } );
    
    $('#logoBorder2').css( { 'float': 'left',
                             'margin': [ config.logoMargin, 'px' ].join(''),
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.greenColor ].join('') } );
    
    $('#logoBorder1').css( { 'float': 'left',
                             '-moz-border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border-radius': [ config.logoBorderRadius, 'px' ].join(''),
                             'border': [ config.logoBorderWidth, 'px solid ', config.blueColor ].join('') } );

    $('#logoContainer')
        .height( $('#logoBorder1').outerHeight( true ) )
        .width( $('#logoBorder1').outerWidth( true ) )
        .css( { 'float': 'left',
                'margin-top': '20px',
                'margin-left': ( ( info.documentWidth - $('#logoBorder1').outerWidth( true ) ) / 2 ) } )
        .after( makeEl('div').css( { 'clear': 'both' } ) );
}

function initializeModalBox() {

    $('body').append(
        makeEl('div').attr( { 'id': 'modalBoxContainer' } ).append(
            makeEl('div').attr( { 'class': 'modalBoxOverlay' } ),
            makeEl('div').attr( { 'id': 'modalBoxContent' } ).append(
                makeEl('div').attr( { 'id': 'modalBoxTitle' } ),
                makeEl('div').attr( { 'id': 'modalBoxForm' } ) ) ) );
}

function makeIntroTextPretty() {

    $( '#introductionText' ).css( { 'margin-top': '30px',
                                    'min-width': '1036px',
                                    'overflow': 'hidden' } );
    
    $( '.introductionText' ).css( { 'text-align': 'center', 'font-size': '20px' } );
    
    $( '.introTextFaq' ).css( { 'float':'left', 'padding': '10px 2px' } );

    $('#faqLink').css( {
        color: 'red',
              } ).hover( setMouseToPointer, setMouseToDefault )
                 .hover( function() { $(this).css( { 'text-decoration': 'underline' } ); },
                         function() { $(this).css( { 'text-decoration': '' } ); } )
                 .click( function() { window.location = 'http://patchworkgardens.net/csaFaq.html'; } );


    var centerMeChildrenWidth = 0;

    $('#centerMe').children().each( function( i ) {
      
        if( i < $('#centerMe').children().length - 1 ) {
            centerMeChildrenWidth += $(this).outerWidth(true);
        }
    } );

    $('#centerMe').css( { 'margin-left': ( ( info.documentWidth - centerMeChildrenWidth ) / 2 ) } );
}
   
function centerFaqText() {

    var centerMeChildrenWidth = 0;

    $('#centerMe').children().each( function( i ) {
      
        if( i < $('#centerMe').children().length - 1 ) {
            centerMeChildrenWidth += $(this).outerWidth(true);
        }
    } );

    $('#centerMe').css( { 'margin-left': ( ( info.documentWidth - centerMeChildrenWidth ) / 2 ) } );

}

function alignModalBox() {

    var content = $('#modalBoxContent');
    var form = $('#modalBoxForm');

    content.css( { top: ( ( info.documentHeight - content.outerHeight( true ) ) / 2 ),
                   left: ( ( info.documentWidth - content.outerWidth( true ) ) / 2 ) } );
         
    if( ! info.modalWait ) {

        $( document ).bind( 'keydown', handleModalKeyPress );
        $( document ).bind( 'click', handleModalMouseClick );
    }
}

function handleModalKeyPress( e ) { if( e.keyCode == 27 ) { closeModalBox(); } }

function handleModalMouseClick( e ) {

    if( ! ( isMouseOnElement( { x: e.pageX, y: e.pageY, el: $( '#modalBoxContent' ) } ) ) ) { closeModalBox(); }
}

function isMouseOnElement( p ) {

    var elementOffset = p.el.offset();

    if( p.x < elementOffset.left || p.y < elementOffset.top ||
        p.x > ( elementOffset.left + p.el.outerWidth( true ) ) ||
        p.y > ( elementOffset.top + p.el.outerHeight( true ) ) ) {

        return false;

    } else { return true; }
}

function closeModalBox() {

    $('#modalBoxTitle').text('');

    $('#modalBoxForm').empty();

    $('#modalBoxContainer').hide();
    
    if( !info.modalWait ) {
        $(document).unbind( 'keydown', handleModalKeyPress );
        $(document).unbind( 'click', handleModalMouseClick );
    } else {
        info.modalWait = false;
    }
}

function makeEl( elementName ) { return $(document.createElement(elementName)); }
function setMouseToPointer() { document.body.style.cursor = 'pointer'; }
function setMouseToDefault() { document.body.style.cursor = 'default'; }


$( window ).load( onPageLoad );
$( window ).resize( onResize );
